package com.trt.eatmeat.sign;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.io.StringReader;

/**
 * @ClassName RawJsonDeserializer
 * @Description TODO
 * @Auther dongzang_fan@trtjk.com
 * @Date 2021/9/28 0028 8:50
 * @Version 1.0
 **/
public class RawJsonDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        long begin = jp.getCurrentLocation().getCharOffset();
        jp.skipChildren();
        long end = jp.getCurrentLocation().getCharOffset();

        if(jp.getCurrentLocation().getSourceRef()  instanceof String){
            String json = jp.getCurrentLocation().getSourceRef().toString();
            return json.substring((int) begin - 1, (int)end);

        }else{
            //json 字段 过长，将不会是字符串 类型，而且stringReader 类型，将不能使用toString 方法
            StringReader reader = (StringReader)jp.getCurrentLocation().getSourceRef();
            reader.reset();
            StringBuilder json = new StringBuilder();
            char[] chars = new char[1024];
            int num =-1;
            do {
                num =reader.read(chars);
                if(num>-1){
                    json.append(new String(chars, 0, num));
                }
            }while (num>-1);
            return json.substring((int) begin - 1, (int)end);
        }

    }
}
